import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/AdminBroder',
    name: 'AdminBroder',
    component: () => import('../components/AdminBroder.vue'),
    redirect: { name: 'AdminPage' },
    meta: { requiresAuth: true },
    children: [
        {
        path: '/AdminMerchandise',
        name: 'AdminMerchandise',
        component: () => import('../views/AdminMerchandise.vue'),
        meta: { requiresAuth: true },
      },
      {
        path: '/AdminCategory',
        name: 'AdminCategory',
        component: () => import('../views/AdminCategory.vue'),
        meta: { requiresAuth: true },
      },
      {
        path: '/AdminUser',
        name: 'AdminUser',
        component: () => import('../views/AdminUser.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/AdminOpLog',
        name: 'AdminOpLog',
        component: () => import('../views/AdminOpLog.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/AdminEmployee',
        name: 'AdminEmployee',
        component: () => import('../views/AdminEmployee.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/AdminPage',
        name: 'AdminPage',
        component: () => import('../views/AdminPage.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/',
        redirect: '/AdminPage'
      }
    ]
  },
  {
    path: '/AdminLogin',
    name: 'AdminLogin',
    component: () => import('../views/AdminLogin.vue')
  },
  {
    // 重定向,默认访问/AdminLogin
    path: '/',
    redirect: '/AdminBroder'
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // 检查是否需要进行认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 检查是否存在 JWT 令牌
    if (!localStorage.getItem('jwt_token')) {
      // 如果没有 JWT 令牌,则跳转到登录页面
      next('/AdminLogin')
    } else {
      // 如果有 JWT 令牌,则继续导航
      next()
    }
  } else {
    // 如果不需要认证,则继续导航
    next()
  }
})

export default router
